<template>
    <fieldset>
        <legend>失效函数的应用</legend>
        <h1 class="content">
            {{ content }}
        </h1>
        <button v-for="(item, index) in buttons" :key="index" @click="pageChange(index + 1)"
            :class="{ active: index + 1 === page }">{{ item }}</button>
    </fieldset>
</template>

<script setup>
import {  reactive, ref, watchEffect,watch } from "vue"
import CancelPromise from "./cancelPromise"
let content = ref("")
let page = ref(1)
let buttons = reactive(['第1页', '第2页', '第3页'])



let api1 = signal => new CancelPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('第一页的数据')
    }, 1000)
}, signal)

let api2 = signal => new CancelPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('第二页的数据')
    }, 1500)
}, signal)

let api3 = signal => new CancelPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('第三页的数据')
    }, 2000)
}, signal)

let api = {
    api1,
    api2,
    api3
}



//封装请求页面数的函数
let fetchData = (pageNumber = 1, signal) => (
    api['api' + pageNumber](signal)
        .then(res => {
            content.value = res
        })
)
let pageChange = (Number) => {
    page.value = Number

}
watchEffect((oninvalidate) => {
    let abortController = new AbortController()
    let signal = abortController.signal
    fetchData(page.value, signal)
    oninvalidate(() => {
        abortController.abort()
    })
})




</script>

<style>
.active {
    background-color: pink;
}
</style>


